<template>
	<view class="page_box">
		<view class="head_box">
			<!-- tab -->
			<!-- <view class="order-nav u-flex">
				 <scroll-view style="margin: 30rpx; white-space: nowrap;" :scroll-x="true" v-for="nav in orderState">
					<block>
						<view class="item-title"  @tap="onNav(nav.type)">{{ nav.title }}</view>
						<view class="nav-line" :class="{ 'line-active': orderType == nav.type }"></view>
					</block>
				</scroll-view>
			</view> -->
			<scroll-view scroll-x class="scrollview-box" >
			  <block v-for="item in orderState">
				<view class="item">
				  <view class="item-title" :class="{ 'line-active': status == item.type }" :style="{'color':status == item.type ? $COLOR : ''}"  @tap="onNav(item.type)">{{ item.title }}</view>
				</view>
				
			  </block>
			</scroll-view>
		
			
		</view>

		<view class="content_box">
			<scroll-view scroll-y="true" enable-back-to-top class="scroll-box" refresher-enabled="true" :refresher-triggered="trigger"  @refresherrefresh="refresherrefresh">
				<!-- 订单列表 -->
				<view class="order-list" v-for="(item, orderIndex) in orderList" :key="item.id">
					<view class="order-head u-flex u-row-between">
						<text class="no">订单编号：{{ item.ordercode }}</text>
						<text class="state">{{getstatus(item.status,item.contractDeductSignStatus)}} </text>
					</view>
					<view class="goods-order" @tap.stop="jump('/pages/order/detail', { id: item.id })">
						<view class="order-content">
							<shopro-mini-card :order="item">
							</shopro-mini-card>
						</view>
					</view>
					<view class="">
						<!-- <view class="all-msg u-flex font-OPPOSANS">
							优惠：
							<text class="all-unit">￥</text>
							{{ order.discount_fee }} ，运费：
							<text class="all-unit">￥</text>
							{{ order.dispatch_amount }} ，{{ order.status <= 0 ? '需付款' : '实付款' }}：
							<view class="all-money font-OPPOSANS">{{ order.total_fee }}</view>
						</view> -->

						<!-- 按钮 -->
					<view>
					    <scroll-view class="btns" scroll-x >
								<button class="btn" :style="{background: $COLOR}"  size="mini" v-if="item.mylContractSignUrl && item.status < 9 && item.contractDeductSignStatus == 1 && item.esignFaceUrl == null"
								@tap="goExteriorPage(item.mylContractSignUrl)">签署合同</button>
								
								<button class="btn" :style="{background: $COLOR}"  size="mini" v-if=" item.status < 9 && item.contractDeductSignStatus == 1 && item.esignFaceUrl != null"
								@tap="goExteriorPage(item.esignFaceUrl)">签署E签宝合同</button>
								
								<button class="btn" :style="{background: $COLOR}"  size="mini" v-if="item.renewMylContractSignUrl && item.status < 9 && item.renewContractDeductSignStatus == 1 "
								@tap="goExteriorPage(item.renewMylContractSignUrl)">签署蚂蚁链合同</button>
								
								 
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.esignContractFile && item.esignContractFile.downloadUrl"
								@tap="EQianbao(item.esignContractFile.downloadUrl)">查看合同</button>
								
								<button class="btn"  :style="{background: $COLOR}" size="mini" v-if="item.mylOrderCharging != null && item.mylOrderCharging.payStatus == 0 "
								@tap="pageaymentContract(item.mylOrderCharging)">支付合同金额</button>
														  
								<button class="btn"  :style="{background: $COLOR}" size="mini" v-if="item.aliPageSign && item.isAgreement == 0"
								 @tap="aliPageSignTap(item.aliPageSign)">签署代扣</button>
								
							<!-- 	<button class="btn"  size="mini" v-if="item.paymentParams == null && item.replenish != 1 && item.status < 3"
								@tap="onBuy(item.id)">冻结押金</button> -->
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.human == 0  && item.replenish != 1 && item.orderType == 2"
								@tap="jump('/pages/user/verifyIdentity/index',{oid:item.id})" >人脸审核</button>
	
								<!-- <button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.productOrderRecordVoList.length > 0 && item.productOrderRecordVoList[0].payment == 0"
								@tap="onReplenish(item)">支付金额</button> -->
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.productOrderRecordVoList.length > 0 && (item.status<8 || item.status==13)"
								@tap="billnavigate(item.id)">付款计划</button>
								
							<!-- 	<button class="btn"  size="mini" v-if="item.productOrderRecordVoList.length > 0 && (item.status<8 || item.status==13)"
								@tap="billnavigate(item.id)">账单详情</button>
								 -->
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="(item.status == 4 || item.status==6) && item.flowOne!=null" 
								@tap="express(item)">查看物流</button>
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.status == 4"
								@tap="confirmReceipt(item.id)">确认收货</button>
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.status == 5"
								onTap="navigateTo">归还物品</button>
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="(item.status == 1 || item.status == 2) && item.replenish != 1"
								@tap="onCancel(item)">申请取消</button>
	
								<button class="btn" :style="{background: $COLOR}" size="mini" v-if="item.status == 14"
								onTap="noCancel">撤销申请</button>
								
								<!-- <button class="btn"  size="mini" a:if="{{item.status != 1}}"
								onTap="navigateTo" data-url="{{url.detail}}" data-param="{{item.params.id}}">再次下单</button> -->
	
								<button class="btn" :style="{background: $COLOR}" size="mini"
								@tap="makePhoneCall" >联系商家</button>
							</scroll-view>
					</view>
					</view>
				</view>
				
				 <!--  申请取消弹窗 -->
				    <view class="pop" v-if="popShow">
				      <view class="popCon">
				        <view>
				          <view class="popCon_tit">请选择取消原因</view>
				            <label class="radio_min" v-for="(item,index) in items" :key="index">
								<u-radio-group v-model="value">
									<u-radio 
										:name="item.name"
										@change="radioChange" 
										:disabled="item.disabled"
									>
										{{item.name}}
									</u-radio>
								</u-radio-group>
				              <!-- <radio :value="item.name" :checked="item.checked" :disabled="item.disabled" /> -->
				              <!-- <text class="radiomin_text">{{item.value}}</text> -->
				            </label>				
				          <view class="pop_btn">
				            <view class="pop_btnMin pop_btnN" @tap="popCancelBtn">取消</view>
				            <view class="pop_btnMin pop_btnY" @tap="popAffirmBtn">确定</view>
				          </view>
				        </view>
				      </view>
				    </view>


				<!-- 空白页 -->
				<shopro-empty v-if="isEmpty" :image="$IMAGE_URL + '/empty_groupon.png'"
					tipText="暂无商品，还有更多好货等着你噢~"></shopro-empty>
				<!-- 更多 -->
				<u-loadmore v-show="orderList.length" height="80rpx" :status="loadStatus" icon-type="flower"
					color="#ccc" />
			</scroll-view>
		</view>
	</view>
</template>

<script>
	export default {
		components: {},
		data() {
			return {
				isEmpty: false,
				loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
				rows: 10,
				page: 1,
				status: -2,
				trigger:false,
				orderList: [],
				value:'计划有变',
				orderState: [{
						id: 0,
						title: '全部',
						type: -2
					},
					{
						id: 1,
						title: '待付款',
						type: 1
					},
					{
						id: 1,
						title: '待审核',
						type: 2
					},
					{
						id: 1,
						title: '待签署',
						type: 40
					},
					{
						id: 2,
						title: '待发货',
						type: 3
					},
					{
						id: 3,
						title: '待收货',
						type: 4
					},
					{
						id: 4,
						title: '待归还',
						type: 5
					},
					{
						id: 4,
						title: '已完成',
						type: 7
					},
					{
						id: 8,
						title: '买断订单',
						type: 8
					},
					{
						id: 4,
						title: '已关闭',
						type: 12
					},
					{
						id: 4,
						title: '申请取消',
						type: 14
					}
				],
				items: [
					  { name: '计划有变', value: '计划有变' },
					  { name: '预收租金/补押金', value: '预收租金/补押金' },
					  { name: '运费问题', value: '运费问题' },
					  { name: '审核时间过长', value: '审核时间过长' },
					  { name: '商家没货/服务态度问题', value: '商家没货/服务态度问题' },
				],
				popShow: false,
				causeCon: '计划有变',
				cancelId: '',
				cancelStatus: ''
			};
		},
		filters: {
		  
		},
		computed: {
		    stateTitle(status) {
				return(status)=>{
					var title = this.orderState.find(item=> item.type == status).title
					return title;
				}
		    },
			getstatus(status, contractDeductSignStatus) {
				return(status, contractDeductSignStatus)=>{
			    switch (status) {
			        case 1:
			            return "待付款";
			        case 2:
			            return "待审核";
			        case 3:
			          if (contractDeductSignStatus == 2) {
			            return '待发货'
			          } else if (contractDeductSignStatus == 1) {
			            return '待签署'
			          } else {
			            return '待生成合同'
			          }
			        case 4:
			            return "待收货";
			        case 5:
			            return "待归还";
			        case 6:
			            return "归还中";
			        case 7:
			            return "交易完成";
			        case 8:
			            return "买断订单";
			        case 9:
			            return "订单关闭（用户）";
			        case 10:
			            return "订单关闭（系统）";
			        case 11:
			            return "订单关闭（商家）";
			        case 13:
			            return "已逾期";
			        case 14:
			            return "申请关闭";
			    }
				}
			},
		},
		// onBackPress(options) {
		// 	if (options.from === 'navigateBack') {
		// 		return false;
		// 	}
		// 	// 这里使用重定向比较好，不信可以自己多试几种，其余跳转方法在文章底部哦
		// 	uni.redirectTo({ 
		// 		url: '/pages/index/index'
		// 	})
		// 	return true;
		// },
		

		
		created() {
			if (this.$Route.query.type) {
				this.status = this.$Route.query.type;
			}
			this.orderList = [];
			this.page = 1;
			this.getOrderList();
		},
		methods: {
			makePhoneCall(){
				uni.makePhoneCall({
					phoneNumber:this.$PLANE_PHONE,
					success:function(){
						console.log('拨打电话成功');
					},
					fail() {
						console.log('打电话失败了');
					}
				})
			},
			// 下拉刷新
			refresherrefresh() {
				this.trigger = true;
				this.page = 1;
				this.getOrderList();
			},
			jump(path, parmas) {
				this.$Router.push({
					path: path,
					query: parmas
				});
			},

			// tab切换
			onNav(status) {
				console.log(status)
				if (this.status !== status) {
					this.status = status;
					this.status = status
					this.orderList = [];
					this.page = 1;
					this.getOrderList();
				}
			},
			billnavigate(oid){
				uni.navigateTo({
				    url:`/pages/order/bill/index?param=`+ oid
				})
			},
			express(item){
				uni.navigateTo({
				    url:`/pages/order/express/index?param=${encodeURIComponent(JSON.stringify(item))}`
				})
			},
			// 确认收货
			confirmReceipt(id) {
				this.$http('order.receiving', {
					id:id
				}, '加载中...').then(res => {	  
					if (res.code == 200) {
						this.$u.toast("提交成功");
						this.getOrderList()
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			// 订单列表
			getOrderList() {
				let that = this;
				let loading = '加载中...';
				if(that.trigger){
					loading = ''
				}
				that.$http('order.index', {
					status: that.status,
					rows: that.rows,
					page: that.page
				}, loading).then(res => {
					if (res.code === 200) {
						that.orderList = res.data.list;
						that.orderList.forEach(item=>{
							item.paramsOld = item.params;
							item.params = JSON.parse(item.params);
							item.createtime = this.upTime("%Y-%M-%D %h:%m:%h", item.createtime);
							item.starttime = item.starttime ? this.upTime("%Y-%M-%D", item.starttime) : '';
							item.endtime = item.endtime ? this.upTime("%Y-%M-%D", item.endtime) : '';
							if(item.status==4 && item.productOrderShipment!=null){
								item.flowOne = {
									id:item.id,
									receiverPhone:item.phone.slice(-4, item.phone.length),
									com:item.productOrderShipment.company,
									no:item.productOrderShipment.number,
								}
							}else if(item.status==6 && item.productOrderRecycle!=null){
								item.flowOne = {
									id:item.id,
									receiverPhone:item.shopsVo.phone.slice(-4, item.phone.length),
									com:item.productOrderRecycle.company,
									no:item.productOrderRecycle.number,
								}
							} 
							else {
								item.flowOne = null
							}
						})
						that.isEmpty = !that.orderList.length;
						that.totalPage = res.data.totalPage;
						uni.stopPullDownRefresh();
					}
					that.trigger=false
				});
			},
			 // 取消原因选择
			radioChange(e){
			    this.causeCon= e
			  
			},
		upTime(format,time) {
			if(!time) {
				return ''
			}
			// let format = "%Y-%M-%D %h:%m:%s"
			format = format ? format: "%Y-%M-%D"
			time = time.toString().length == 10 ? time*1000:time
			let dataTime = new Date(time)
			let year = dataTime.getFullYear()
			let month = (dataTime.getMonth() + 1).toString().padStart(2, 0)
			let day = dataTime.getDate().toString().padStart(2, 0)
			let Hours = dataTime.getHours().toString().padStart(2, 0)
			let Minutes = dataTime.getMinutes().toString().padStart(2, 0)
			let Seconds = dataTime.getSeconds().toString().padStart(2, 0)
			format = format.replace(/(%Y|%M|%D|%h|%m|%s)/g, (n) => {
				return {
					'%Y': year, '%M': month, '%D': day, '%h': Hours, '%m': Minutes, '%s': Seconds,
				}[n]
			})
				return format
		
		},
			// 关闭取消弹窗
			popCancelBtn(){
				this.cancelId= '',
				this.cancelStatus= '',
				this.causeCon= '计划有变',
				this.popShow= false
			},
			// 确认取消
			popAffirmBtn(){
				let that = this
			  console.log(that.causeCon,that.cancelId,that.cancelStatus,'原因');
				
			  if (that.cancelStatus == 1 || that.cancelStatus == 2 || that.cancelStatus == 3) {
				  that.$http('order.requestCanOrder', {
				  	oid:that.cancelId,
				  	cont: that.causeCon
				  }, '加载中...').then(res => {
				  	if (res.code === 200) {
						that.$u.toast('申请成功！');
						that.popCancelBtn();
						that.getOrderList();
					
				  	}
				  });
			  }
			},
			// 加载更多
			loadMore() {
				if (this.page < this.totalPage) {
					this.page++;
					this.getOrderList();
				}
			},
			// 关闭订单, 申请取消
			onCancel(e) {
				let id = e.id;
				let status = e.status;		
				this.cancelId = id,
				this.cancelStatus = status,
				this.popShow = true
			},
			 noCancel(e){
				 console.log(e)
			        let cancelRequests = e.target.dataset.item.productOrderCancelRequests
			        let id = cancelRequests[cancelRequests.length-1].id
			        my.confirm({
			            title: '温馨提示',
			            content: '是否撤回订单取消申请',
			            confirmButtonText: '立即撤回',
			            cancelButtonText: '暂不撤回',
			            success: (result) => {
			                if (result.confirm) {
			                    app.order.repeal(id)
			                    .then(red=>{
			                        if(res.code==200) {
			                            my.alert({
			                                title: "撤回成功",
			                                success: () => {
			                                    this.resetOrder()
			                                }
			
			                            });
			                        }
			                    })
			                }
			            },
			        });
			    },
			
			goExteriorPage(signUrl){
				window.location.href = signUrl;
				// plus.runtime.openURL(signUrl, function(res) {
				//    console.log(res);  
				// }); 
				// uni.navigateToMiniProgram({
				//   appId: '2021001152620480',
				//   path:`pages/signH5/index?signUrl=${signUrl}`,
				//   success: (res) => {
				// 	console.log(JSON.stringify(res))
				//   },
				//   fail: (res) => {
				// 	console.log(JSON.stringify(res));
				// 	// my.alert({
				// 	//   title: JSON.stringify(res),
				// 	// });
				//   }
			 //  });
			},
			// e签宝
			EQianbao(url){
			  if(!url){
			    this.$message.wraning('未获取到链接！');
			    return;
			  }
			  window.location.href = url;
			  // plus.runtime.openURL(url, function(res) {
			  //    console.log(res);  
			  // }); 
			
			},
			// 冻结
			onBuy(oid) {
				var that = this;
				this.$http("goods.freeze", {id:oid}).then((pay) => {
					console.log('支付',pay)
					uni.requestPayment({
						provider: 'alipay',
						orderInfo: pay.data, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
						success: function (res) {
							that.$u.toast('支付成功！');
							that.jump('/pages/order/list', { type: '-2' })
							console.log('success:' + JSON.stringify(res));
						},
						fail: function (err) {
							that.jump('/pages/order/list', { type: '-2' })
							console.log('fail:' + JSON.stringify(err));
						}
					});
								
				})
			},
			// 支付合同金额
			pageaymentContract(data) {
				console.log('支付合同金额',data.zfbUrl)
				window.location.href = data.zfbUrl;
			},
			// 签署代扣
			aliPageSignTap(data) {
				let url = "alipays://platformapi/startapp?appId=60000157&appClearTop=false&startMultApp=YES&sign_params=";
				window.location.href = url+data;
				
			},
				
			 // 支付
			onReplenish(val) {
				var productOrderRecordVoList = val.productOrderRecordVoList[0]
				let that = this
				that.$http("goods.alipay", {id:productOrderRecordVoList.id,oid:productOrderRecordVoList.oid}).then((pay) => {
					console.log('支付宝支付',pay)
					window.location.href = pay.data;
				})
				// this.$http("goods.alipay", {id:productOrderRecordVoList.id,oid:productOrderRecordVoList.oid}).then((pay) => {
				// 	console.log('支付',pay)
				// 	uni.requestPayment({
				// 		provider: 'alipay',
				// 		orderInfo: pay.data, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
				// 		success: function (res) {
				// 			that.$u.toast('支付成功！');
				// 			console.log('success:' + JSON.stringify(res));
				// 		},
				// 		fail: function (err) {
				// 			that.$u.toast('支付失败！');
				// 			console.log('fail:' + JSON.stringify(err));
				// 		}
				// 	});
								
				// })
			},
		}
	};
</script>

<style lang="scss">
.item-title {
	font-size: 30rpx;
	font-weight: 400;
	color: #a7a7a7;
	line-height: 76rpx;
}
.nav-line {
	height: 4rpx;
	background: #fff;
}
.line-active {
	// background:  #ffcb31;
	color: #ffcb31;
	  font-weight: bold;
}
	.order-list {
		background: #fff;
		margin: 20rpx 0;

	

		.order-head {
			padding: 0 25rpx;
			height: 77rpx;
			// border-bottom: 1rpx solid #dfdfdf;

			.no {
				font-size: 26rpx;
				color: #999;
			}

			.state {
				font-size: 26rpx;
				color: #999;
			}
		}

		.goods-order {
			// border-bottom: 1px solid rgba(223, 223, 223, 0.5);
			padding: 20rpx 20rpx 0;
			margin-bottom: 20rpx;
		}
	}
	
.btns {
	white-space: nowrap;
	height: 80rpx;
	padding: 0 20rpx;
	box-sizing: border-box;
	display: flex;
	justify-content: flex-end;
	align-content: flex-end;
	text-align: right;
}

.btn {
	margin-bottom: 100rpx;
	// float: right;
    flex-shrink:0;
    border-radius: 15rpx;
    margin-left: 20rpx;
    padding: 0rpx 20rpx;
    color: #FFF;
	background-color: #ffcb31;
}
.scrollview-box{
	background: #fff;
	white-space: nowrap; // 滚动必须加的属性
	width: 100%;
	height: 100rpx;
	line-height: 100rpx;
}
.item{
	margin-left: 30rpx;
	margin-right: 30rpx;
	display: inline-flex;  // item的外层定义成行内元素才可进行滚动 inline-block / inline-flex 均可
}
/* 申请取消弹窗 */
.pop{
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 100;
  display: flex;
  justify-content: center;
  box-sizing: border-box;
  padding-top: 25vh;
}
.popCon{
  width: 70vw;
  height: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  position: relative;
  animation: popC 0.1s linear;
}
@keyframes popC{
  0%{
    transform: scale(0.8);
  }
  100%{
    transform: scale(1);
  }
}
.popCon_tit{
  width: 100%;
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  border-bottom: 1rpx solid #e7e6e6; 
  margin-bottom: 30rpx;
  font-weight: bold;
  letter-spacing: 2rpx;
}
.radio_min{
  width: 80%;
  margin: 0 auto;
  display: flex;
  margin-bottom: 20rpx;
  align-items: center;
}
.radiomin_text{
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #696767;
}
.pop_btn{
  width: 100%;
  height: 100rpx;
  position: absolute;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  border-top: 1rpx solid #e7e6e6;
}
.pop_btnMin{
  width: 50%;
  line-height: 100rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: bold;
  letter-spacing: 4rpx;
}
.pop_btnN{
  color: rgb(240, 17, 17);
  border-right: 1rpx solid #e7e6e6;
}
.pop_btnY{
  /* color: rgb(51, 233, 111); */
}
</style>
